import {
    Index
} from './index.model'
import {
    Base
} from '../../utils/base'
const base = new Base()
const index = new Index()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        companylist: [], // 检车站列表
        regionName: ['地区'], // 地区名称列表
        regionId: ['0'], // 地区ID列表
        regionIndex: 0, // 地区picker组件索引值
        selectedRegionId: 0, // 选择的地区ID
        vehicleName: ['车型'], // 车型名称列表
        vehicleId: ['0'], // 车型ID列表
        vehicleIndex: 0, // 车型picker组件索引值
        selectedVehicleId: 0, // 选择的车型ID
        distanceName: ['距离', '2km', '5km', '10km', '20km', '50km'], // 距离名称列表
        distanceId: ['0', '2', '5', '10', '20', '50'], // 距离ID列表
        distanceIndex: 0, // 距离picker组件索引值
        selectedDistanceId: 0, // 选择的距离ID
        userLng: 0, // 用户经度
        userLat: 0, // 用户纬度
        showInfo: true, // 是否显示搜索结果
        resultsNumber: 0, // 搜索结果数量
        inputValue: '', // 输入信息
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        let that = this
        that._loadData()
    },

    onShow(){
        let that = this
        that.getTabBar().init() // 切换标签
    },

    /**
     * 获取所有数据
     */
    _loadData: function () {
        let that = this
        that.getCompanyData()
        that.getRegionData()
        that.getVehicleData()
        that.authLocation()
    },

    /**
     * 获取检车站列表
     * @param {string} company_name 检车站名称
     */
    getCompanyData: function (company_name = '') {
        wx.showLoading({
            title: '正在加载数据',
        })
        let that = this,
            param = {
                company_name: company_name, // 检车站名称
                districtId: that.data.selectedRegionId, // 地区ID
                vehicleId: that.data.selectedVehicleId, // 车型ID
                distanceId: that.data.selectedDistanceId, // 距离
                userLng: that.data.userLng, // 用户经度
                userLat: that.data.userLat, // 用户纬度
            }
        index.getCompanyData(param).then((res) => {
            if (res.data.count == 0) {
                that.setData({
                    showInfo: false,
                })
            }
            that.setData({
                companylist: res.data.list,
                resultsNumber: res.data.count
            })
        }).then(() => {
            wx.stopPullDownRefresh()
            wx.hideLoading()
        })
    },

    /**
     * 获取地区列表
     */
    getRegionData: function () {
        let that = this
        index.getRegionData().then((res) => {
            let regionName = that.data.regionName,
                regionId = that.data.regionId
            for (let i = 0; i < res.data.length; i++) {
                regionName.push(res.data[i]['name'])
                regionId.push(res.data[i]['id'])
            }
            that.setData({
                regionName: regionName,
                regionId: regionId,
            })
        })
    },

    /**
     * 获取车型列表
     */
    getVehicleData: function () {
        let that = this
        index.getVehicleData().then((res) => {
            let vehicleName = that.data.vehicleName,
                vehicleId = that.data.vehicleId
            for (let i = 0; i < res.data.length; i++) {
                vehicleName.push(res.data[i]['title'])
                vehicleId.push(res.data[i]['id'])
            }
            that.setData({
                vehicleName: vehicleName,
                vehicleId: vehicleId,
            })
        })
    },

    /**
     * 授权位置信息
     */
    authLocation: function () {
        let that = this
        // 是否授权
        wx.getSetting({
            success: (res) => {
                // 没有位置权限
                if (!res.authSetting['scope.userLocation']) {
                    // 主动向用户获取位置权限
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: () => {
                            that.getUserLocation().then(() => {
                                that.getCompanyData()
                            })
                        },
                        fail: () => {
                            if (!wx.getStorageSync('isAuthLocation')) {
                                wx.showToast({
                                    title: '位置信息无法使用，可在设置里重新授权',
                                    icon: 'none'
                                })
                                wx.setStorageSync('isAuthLocation', true)
                                console.log('拒绝授权')
                            }
                        }
                    })
                } else {
                    that.getUserLocation().then(() => {
                        that.getCompanyData()
                    })
                }
            }
        })
    },

    // 获取用户经纬度
    getUserLocation: function () {
        let that = this
        return new Promise(function (resolve, reject) {
            wx.getLocation({
                type: 'gcj02',
                success: (res) => {
                    that.setData({
                        userLng: res.longitude,
                        userLat: res.latitude,
                    })
                    resolve(res)
                },
                fail: () => {
                    reject("系统异常，请重试！")
                }
            })
        })
    },

    /**
     * 选择地区
     * @param {*} event
     */
    selectRegion: function (event) {
        let that = this,
            selectedRegionId = that.data.regionId[event.detail.value]
        that.setData({
            regionIndex: event.detail.value,
            selectedRegionId: selectedRegionId
        })
        that.getCompanyData()
    },

    /**
     * 选择车型
     * @param {*} event
     */
    selectVehicle: function (event) {
        let that = this,
            selectedVehicleId = that.data.vehicleId[event.detail.value]
        that.setData({
            vehicleIndex: event.detail.value,
            selectedVehicleId: selectedVehicleId
        })
        that.getCompanyData()
    },

    /**
     * 选择距离
     * @param {*} event
     */
    selectDistance: function (event) {
        let that = this,
            selectedDistanceId = that.data.distanceId[event.detail.value]
        that.setData({
            distanceIndex: event.detail.value,
            selectedDistanceId: selectedDistanceId,
        })
        // 是否授权
        wx.getSetting({
            success: (res) => {
                if (!res.authSetting['scope.userLocation']) {
                    wx.showModal({
                        title: '提示',
                        content: '请授权使用位置信息',
                        success: (res) => {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: () => {
                                        wx.removeStorageSync('isAuthLocation')
                                        that.getUserLocation().then(() => {
                                            that.getCompanyData()
                                        })
                                    }
                                })
                            } else if (res.cancel) {
                                that.setData({
                                    distanceIndex: 0,
                                    selectedDistanceId: 0,
                                })
                            }
                        }
                    })
                } else {
                    that.getUserLocation().then(() => {
                        that.getCompanyData()
                    })
                }
            }
        })
    },

    /**
     * 搜索检车站名称
     * @param {*} event
     */
    onSearchCompany: function (event) {
        let that = this
        that.setData({
            showInfo: false
        })
        that.getCompanyData(event.detail.value)
    },

    /**
     * 点击关闭图标
     */
    onCloseIcon: function () {
        let that = this
        that.setData({
            showInfo: true,
            inputValue: ''
        })
    },

    /**
     * 点击'申请检车'事件
     * @param {*} event
     */
    onApplyInspectionCar: function (event) {
        let id = base.getDataSet(event, 'id')
        wx.navigateTo({
            url: `../indexde/indexde?company_id=${id}`,
            // url: `../subscribe/subscribe?company_id=${id}`,
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        let that = this
        that.setData({
            regionIndex: 0,
            selectedRegionId: 0,
            vehicleIndex: 0,
            selectedVehicleId: 0,
            distanceIndex: 0,
            selectedDistanceId: 0,
            showInfo: true,
            inputValue: ''
        })
        that.getCompanyData()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: '哈尔滨机动车检测协会提供支持',
            path: '/pages/index/index'
        }
    }
})